package com.dtdream.emr;

import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;

public final class WMConcat extends UDAF {

    public static class DtWMConcatState {
        private StringBuilder resultBuilder;
        private boolean isInit;
        private String separator;
    }

    public static class DtWMConcatEvaluator implements UDAFEvaluator {

        DtWMConcatState state;

        public DtWMConcatEvaluator() {
            super();
            state = new DtWMConcatState();
            init();
        }

        public void init() {
            state.resultBuilder = new StringBuilder();
            state.isInit = true;
            state.separator = "";
        }

        public boolean iterate(String i, String s) {
            if (s != null) {
                state.resultBuilder.append(i).append(s);
                state.isInit = false;
                state.separator = i;
            }
            return true;
        }

        public DtWMConcatState terminatePartial() {
            // This is SQL standard - average of zero items should be null.
            return state.isInit == true ? null : state;
        }

        public boolean merge(DtWMConcatState o) {

            if (o != null) {
                state.resultBuilder.append(o.resultBuilder);
                state.isInit = false;
            }

            return true;
        }

        public String terminate() {
            int i = state.resultBuilder.indexOf(state.separator);
            // This is SQL standard - average of zero items should be null.
            return state.isInit == true ? "" : state.resultBuilder.substring(i + state.separator.length());
        }
    }
}